from ajax_select import LookupChannel
from django.utils.html import escape
from django.db.models import Q
from models import *


class LocalidadLookup(LookupChannel):

    model = Localidad

    min_length = 1

    def get_query(self,q,request):
        if q.isdigit():
            return Localidad.objects.filter(Q(codigo_postal=int(q)) | Q(nombre__icontains=q)).order_by('nombre')
        else:
            return Localidad.objects.filter(Q(nombre__icontains=q)).order_by('nombre')
 
    def get_result(self,obj):
        """ result is the simple text that is the completion of what the person typed """
        return self.format_item_display(obj)

    def format_match(self,obj):
        """ (HTML) formatted item for display in the dropdown """
        return self.format_item_display(obj)

    def format_item_display(self,obj):
        """ (HTML) formatted item for displaying item in the selected deck area """
        if obj.codigo_postal:
            return u"%s %s" % (escape(obj.codigo_postal),escape(obj.nombre))
        else:
            return escape(obj.nombre)


    def check_auth(self,request):
        pass